package com.snow.useviewdemo.html;

import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.snow.common.base.BaseBasesActivity;
import com.snow.useviewdemo.R;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;

import butterknife.ButterKnife;

/**
 * author : zyt
 * e-mail : 632105276@qq.com
 * date   : 2019-09-09
 * desc   :通过webview加载pdf文件====加载x5内核失败所以暂时加载不成功
 */
public class WebViewPDFAct extends BaseBasesActivity {
    TbsReaderView tbsReaderView;

    @Override
    protected int getContentViewId() {
        return R.layout.act_html_webview_pdf;
    }

    RelativeLayout root_view;

    @Override
    protected void initView() {
        root_view = findViewById(R.id.root_view);
        tbsReaderView = new TbsReaderView(this, readerCallback);

        root_view.addView(tbsReaderView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        String selectFilePath = getIntent().getStringExtra("selectFilePath");
        openFile(selectFilePath);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    private void openFile(String url) {
        File file = new File(url);
        if (!file.exists()) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
        }
        Bundle bundle = new Bundle();
        bundle.putString("filePath", url);
        bundle.putString("tempPath", Environment.getExternalStorageDirectory().getPath());
        boolean result = tbsReaderView.preOpen(parseFormat(parseName(url)), false);
        if (result) {
            tbsReaderView.openFile(bundle);
        }
    }

    private String parseFormat(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    TbsReaderView.ReaderCallback readerCallback = new TbsReaderView.ReaderCallback() {
        @Override
        public void onCallBackAction(Integer integer, Object o, Object o1) {

        }
    };

    private String parseName(String url) {
        String fileName = null;
        try {
            fileName = url.substring(url.lastIndexOf("/") + 1);
        } finally {
            if (TextUtils.isEmpty(fileName)) {
                fileName = String.valueOf(System.currentTimeMillis());
            }
        }
        return fileName;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁界面的时候一定要加上，否则后面加载文件会发生异常。
        tbsReaderView.onStop();
    }

    class JsObject {

        @JavascriptInterface
        public void startPhotoActivity(String jsonData, int position) {
            Toast.makeText(WebViewPDFAct.this, "当前地址：===" + position + "===" + jsonData, Toast.LENGTH_SHORT).show();
        }
    }


}
